package org.dromara.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.WalletChange;
import org.dromara.business.domain.bo.WalletChangeBo;
import org.dromara.business.domain.vo.WalletChangeVo;
import org.dromara.business.mapper.WalletChangeMapper;
import org.dromara.business.service.WalletChangeService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 钱包变动记录Service业务层处理
 *
 * @author zlj
 * @date 2024-08-20
 */
@RequiredArgsConstructor
@Service
public class WalletChangeServiceImpl extends ServiceImpl<WalletChangeMapper, WalletChange> implements WalletChangeService {

    private final WalletChangeMapper baseMapper;

    private final SysUserMapper sysUserMapper;


    /**
     * 查询钱包变动记录
     */
    @Override
    public WalletChangeVo queryById(Long walletChangeId) {
        return baseMapper.selectVoById(walletChangeId);
    }

    /**
     * 查询钱包变动记录列表
     */
    @Override
    public TableDataInfo<WalletChangeVo> queryPageList(WalletChangeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WalletChange> lqw = buildQueryWrapper(bo);
        Page<WalletChangeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询钱包变动记录列表
     */
    @Override
    public List<WalletChangeVo> queryList(WalletChangeBo bo) {
        LambdaQueryWrapper<WalletChange> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WalletChange> buildQueryWrapper(WalletChangeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WalletChange> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, WalletChange::getUserId, bo.getUserId());
        lqw.eq(bo.getChangeType() != null, WalletChange::getChangeType, bo.getChangeType());
        lqw.eq(bo.getChangeCount() != null, WalletChange::getChangeCount, bo.getChangeCount());
        lqw.eq(bo.getChangeBefore() != null, WalletChange::getChangeBefore, bo.getChangeBefore());
        lqw.eq(bo.getChangeAfter() != null, WalletChange::getChangeAfter, bo.getChangeAfter());
        lqw.orderByDesc(WalletChange::getCreateTime);
        return lqw;
    }

    /**
     * 新增钱包变动记录
     */
    @Override
    public Boolean insertByBo(WalletChangeBo bo) {
        WalletChange add = MapstructUtils.convert(bo, WalletChange.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setWalletChangeId(add.getWalletChangeId());
        }
        return flag;
    }

    /**
     * 修改钱包变动记录
     */
    @Override
    public Boolean updateByBo(WalletChangeBo bo) {
        WalletChange update = MapstructUtils.convert(bo, WalletChange.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WalletChange entity) {

    }

    /**
     * 批量删除钱包变动记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 公共方法-用户账户变动行为记录
     *
     * @param userId 用户id
     * @param money  变动金额(变动值,永远为正值)
     * @param flag   true:代表增加  false: 代表减少
     * @param type   1. 平台打款    2. 发起提现  3. 提现返还(提现申请驳回)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeUserAmount(String userId, BigDecimal money, Boolean flag, int type) {
        //校验money值
        if (money.compareTo(BigDecimal.ZERO) < 0) {
            // 金额不能为负数
            throw new RuntimeException("操作失败");
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        //当前账户
        BigDecimal currentAmount = sysUser.getAmount();
        //最新账户
        BigDecimal newAmount;
        if (flag) {
            newAmount = currentAmount.add(money);
        } else {
            newAmount = currentAmount.subtract(money);
        }
        sysUser.setAmount(newAmount);
        sysUserMapper.updateById(sysUser);

//        WalletChange walletChange=new WalletChange();
//        walletChange.setUserId(sysUser.getUserId());
//        walletChange.setChangeType(flag?0:1);
//        walletChange.setChangeOption(type);
//        //变化量
//        walletChange.setChangeCount(money);
//        //变化之前值
//        walletChange.setChangeBefore(currentAmount);
//        //变化之后值
//        walletChange.setChangeAfter(newAmount);
//        this.save(walletChange);
    }

    /**
     * 提现申请打款
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCash(String userId, BigDecimal money) {
        if (money.compareTo(BigDecimal.ZERO) < 0) {
            // 金额不能为负数
            throw new RuntimeException("操作失败");
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        if( money.compareTo(sysUser.getAmount()) >0){
            throw new RuntimeException("申请金额不能大于余额");
        }
        //发起提现
        this.changeUserAmount(userId,money,false,2);
    }
}
